<?php
/**
 * Created by PhpStorm.
 * User: zws
 * Date: 2018/9/8
 * Time: 11:02
 * 添加工单
 */
namespace app\index\service;

use app\common\model\ChargingModel;
use app\common\model\InstrumentModel;
use app\common\model\OrderModel;
use app\common\model\OrderProjectModel;
use app\common\model\ProjectModel;
use app\common\model\OrderParamModel;
use app\common\model\OrderImageModel;
use think\Db;
use think\Exception;

class OrderService
{
    protected static $orderModel;
    /**
     * UserService constructor.
     * @param OrderModel $orderModel
     * @author zws
     */
    public function __construct(OrderModel $orderModel)
    {
        self::$orderModel = $orderModel;
    }

    /**
     * 添加工单并创建检测项目数据
     * @param $param
     * @return bool
     * @author zws
     */
    public function add($param){
        if(empty($param))
        {
            app_fail(9997);
        }
        if(!isset($param['charge_id']) || empty($param['charge_id']))
        {
            app_fail(8993);
        }
        if(!isset($param['project_id']) || empty($param['project_id']))
        {
            app_fail(6997);
        }
        $project_id = $param['project_id'];
        $projectArr = explode(";", $project_id);
        $order = self::$orderModel;
        Db::startTrans();
        try{
            $order->allowField(true)->save($param);
            $addDetection = [];
            $order_id = $order->id;
            foreach ($projectArr as $v)
            {
                $addDetection[] = ['order_id'=>$order_id, 'project_id'=>$v];
            }
            $orderProjectModel = new OrderProjectModel();
            $orderProjectModel->saveAll($addDetection);
            Db::commit();
            $param['order_id'] = $order_id;
            return $param;
        }catch (Exception $e){
            Db::rollback();
            app_fail(9899);//用户编辑失败
        }

    }

    /**
     * 修改工单状态
     * @param $param
     * @return bool
     * @author zws
     */
    public function updateStatus($param)
    {
        if(empty($param))
        {
            app_fail(9997);
        }
        if(!isset($param['order_id']) || empty($param['order_id']))
        {
            app_fail(6996);
        }
        if(!isset($param['status']))
        {
            app_fail(6996);
        }
        $orderModel = self::$orderModel;
        $orderData = $orderModel->where(['id'=>$param['order_id']])->find();
        if(!$orderData)
        {
            app_fail(6999);
        }
        try{
            $orderModel->save(['status'=>$param['status']], ['id'=>$param['order_id']]);
            return [];
        }catch (Exception $e){
            app_fail(9899);//用户编辑失败
        }
    }

    /**
     * 工单列表
     * @param $param
     * @return array
     * @author zws
     */
    public function orderList($param)
    {
        if(!isset($param['page']) || empty($param['page'])){
            $param['page'] = 1;
        }
        if(!isset($param['limit']) || empty($param['limit'])){
            $param['limit'] = 10;
        }
        $orderModel = self::$orderModel;
        $userId = $param['user_id'];
        if(empty($userId))
        {
            app_fail(7999);//用户不存在
        }
        $where = [];
        $where[] = ['user_id', '=', $userId];
        $where[] = ['is_del', '=', 1];
        if(isset($param['status'])){
            if($param['status'] == 1) //未完成
            {
                $where[] = ['status', '<>', '4'];
            }
            if($param['status'] == 2) //已完成
            {
                $where[] = ['status', '=', '4'];
            }
        }
        $orderData = $orderModel->where($where)
            ->page($param['page'], $param['limit'])
            ->order('create_time', 'desc')
            ->select();
        $order_id = [];
        $instrument_id = [];
        $charge_id = [];
        $orderStatus = config('param_config.order_status');
        foreach ($orderData as $k=>$v)
        {
            $orderData[$k]['order_status'] = isset($orderStatus[$v->status]) ?
                $orderStatus[$v->status] : '';
            $order_id[] = $v['id'];
            $instrument_id[] = $v['instrument_id'];
            $charge_id[] = $v['charge_id'];
        }
        //工单对应的检测项目
        $orderProjectModel = new OrderProjectModel();
        $orderProject = $orderProjectModel->where('order_id', 'in', $order_id)->select();
        $project_id = [];
        $orderProjectData = [];
        if($orderProject){
            foreach ($orderProject as $v){
                $project_id[] = $v['project_id'];
            }
        }
        //检测项目数据
        $projectModel = new ProjectModel();
        $projectDataArr = [];
        if($project_id)
        {
            $projectData = $projectModel->where('id', 'in', array_unique($project_id))
                ->field('id,project_name')
                ->select();
            foreach ($projectData as $v){
                $projectDataArr[$v->id] = $v->project_name;
            }
        }
        if($orderProject) {
            foreach ($orderProject as $v) {
                if(isset($projectDataArr[$v->project_id])){
                    $orderProjectData[$v->order_id][] = $projectDataArr[$v->project_id];
                }
            }
        }
        //充电桩数据
        $ChargingModel = new ChargingModel();
        $chargeDataArr = [];
        if($charge_id)
        {
            $ChargingData = $ChargingModel->where('id', 'in', array_unique($charge_id))
                ->field('id,charge_name')
                ->select();
            foreach ($ChargingData as $v){
                $chargeDataArr[$v->id] = $v->charge_name;
            }
        }
        //检测仪器数据
        $instrumentModel = new InstrumentModel();
        $instrumentDataArr = [];
        if($instrument_id)
        {
            $instrumentData = $instrumentModel->where('id', 'in', array_unique($instrument_id))
                ->field('id,instrument_num')
                ->select();
            foreach ($instrumentData as $v){
                $instrumentDataArr[$v->id] = $v->instrument_num;
            }
        }
        $resultData = [];
        foreach ($orderData as $k=>$v)
        {
            $resultData[$k]['id'] = $v->id;
            $resultData[$k]['name'] = $v->name;
            $resultData[$k]['create_time'] = $v->create_time;
            $resultData[$k]['order_status'] = $v->order_status;
            $resultData[$k]['charge_name'] = '';
            $resultData[$k]['instrument_num'] = '';
            $resultData[$k]['projectData'] = [];
            if($chargeDataArr && isset($chargeDataArr[$v->charge_id])){
                $resultData[$k]['charge_name'] = $chargeDataArr[$v->charge_id];
            }
            if($instrumentDataArr && isset($instrumentDataArr[$v->instrument_id])){
                $resultData[$k]['instrument_num'] = $instrumentDataArr[$v->instrument_id];
            }
            if($orderProjectData && isset($orderProjectData[$v->id])){
                $resultData[$k]['projectData'] = $orderProjectData[$v->id];
            }
        }
        return $resultData;
    }

    public function uploadData($param)
    {
        if(empty($param))
        {
            app_fail(9997);
        }
        if(!isset($param['order_id']) || empty($param['order_id']))
        {
            app_fail(6996);
        }
        if(!isset($param['charge_type']) || empty($param['charge_type']))
        {
            app_fail(8994);
        }
        Db::startTrans();
        try{

            if(isset($param['instrument_id']) && $param['instrument_id'])
            {
                $orderModel = self::$orderModel;
                $orderModel->save(['instrument_id'=>$param['instrument_id']], ['id'=>$param['order_id']]);
            }
            //工单参数
            $orderParamModel = new OrderParamModel();
            // 判断是添加还是编辑
            $row = $orderParamModel->where(['order_id' => $param['order_id']])->find();
            if (empty($row)) {
                $orderParamModel->allowField(true)->save($param);
            } else {
                $orderParamModel->allowField(true)->save($param, ['order_id' => $param['order_id']]);
            }
            //上传图片
            if(isset($param['image']) && !empty($param['image']))
            {
                $this->uploadImage($param);
            }
            Db::commit();
            return [];
        }catch (Exception $e){
            Db::rollback();
            app_fail(9899);//用户编辑失败
        }

    }

    /**
     * 上传图片
     * @param $params
     * @author zws
     */
    public function uploadImage($params)
    {
        $files = $params['image'];
        $order_id = $params['order_id'];
        $data = [];
        $imagePath = config('param_config.reportPath');

        foreach($files as $file){
            // 移动到框架应用根目录/uploads/ 目录下
            $info = $file->validate(['ext'=>'jpeg,jpg,png,gif'])->move($imagePath);
            $arr['order_id'] = $order_id;
            if($info){
                $arr['img_url'] = $info->getSaveName();
            }else{
                // 上传失败获取错误信息
                app_fail($file->getError());
            }
            $data[] = $arr;
        }
        $orderImageModel = new OrderImageModel();
        $orderImageModel->saveAll($data);
    }

}